<template>
	<view>
		<!-- #ifdef H5 -->
		<fui-sticky>
			<fui-nav-bar title="我的余额" @leftClick="leftClick">
				<fui-icon name="arrowleft"></fui-icon>
			</fui-nav-bar>
		</fui-sticky>
		<!-- #endif -->

		<view class="box">
			<view class="head">
				<view class="yes1">
					<view class="yes">
						<view
							style="font-size: 26rpx;display: flex; justify-content:space-around; align-items: center;">
							充值余额</view>
					</view>
					<view
						style="display: flex; justify-content:space-around; align-items: center; font-weight: 900;font-size: 50rpx;color: var(--fui-color-primary);;">
						￥{{Number(userInfo?.money?.topup_balance)||0}}
					</view>
				</view>
				<view class="no">
					<view class="yes">
						<view
							style="font-size: 26rpx;display: flex; justify-content:space-around; align-items: center;">
							收入余额</view>
					</view>
					<view
						style="display: flex;justify-content:space-around; align-items: center; text-align:right;font-weight: 900;font-size: 50rpx;color: var(--fui-color-primary);;">
						￥{{Number(userInfo?.money?.income_balance)||0}}
					</view>
				</view>
			</view>
			<view style="display: flex;justify-content: space-between;">
				<view class="yestwo" v-if="!userInfo?.money?.topup_state">
					<view v-if="!config.rechargeRemit" style="font-size: 26rpx;color: var(--fui-color-subtitle);">
						不可提现金额 ￥{{Number(userInfo?.money?.topup_balance)||0}}
					</view>
					<view v-if="!config.rechargeRemit" style="font-size: 24rpx;color: var(--fui-color-subtitle);">
						充值余额不可提现
					</view>
				</view>

				<view class="btn" style="font-size: 26rpx;margin-top: 20rpx;" @click="detail">
					查看明细
				</view>
			</view>

			<fui-section style="padding: 0;margin-top: 40rpx;" color="#fd5531" title="请选择提现金额" isLine></fui-section>
			<view class="rooftype">
				<view class="rooflist">
					<view class="roofitem" v-for="(item,index) in config.assignMoney"
						:class="data.priceIndex == index?'roofactive':''" @click="roof(item,index)">
						<view class="roofprice">
							￥{{item}}
						</view>
						<view class="roofname">
							<!-- {{item.name}} -->
						</view>
					</view>
				</view>
			</view>
			<fui-input v-if="config.customMoney" radius="20" style="margin-top: 20rpx;" backgroundColor="#f3f5f7"
				@click="data.priceIndex = -1, data.price = ''" v-model="data.price" placeholder="其他金额直接输入"></fui-input>
			<fui-section v-if="config.rechargeRemit||userInfo?.money?.topup_state" style="padding: 0;margin-top: 40rpx;"
				color="#fd5531" title="金额类型" isLine></fui-section>
			<fui-radio-group v-if="config.rechargeRemit||userInfo?.money?.topup_state" :modelValue="data.moneyType"
				@change="changemoneyType">
				<fui-label v-for="(item,index) in data.moneyItems" :key="index">
					<fui-list-cell>
						<view class="fui-list__cell">
							<view style="display: flex;justify-content: space-between;align-items: center;">
								<view style="margin-left: 20rpx;">{{item.name}}</view>
							</view>
							<fui-radio v-if="data.radioItems.length>1" :checked="item.checked" :value="item.value">
							</fui-radio>
						</view>
					</fui-list-cell>
				</fui-label>
			</fui-radio-group>

			<!-- 标题 -->
			<fui-section style="padding: 0;margin-top: 40rpx;" color="#fd5531" title="提现方式" isLine></fui-section>
			<!-- 提现方式 -->
			<view class="czfs" style="margin-top: 20rpx;">
				<fui-radio-group :modelValue="payType" @change="changepayType">
					<fui-label v-for="(item,index) in data.radioItems" :key="index">
						<fui-list-cell>
							<view class="fui-list__cell">
								<view style="display: flex;justify-content: space-between;align-items: center;">
									<image style="width: 60rpx;height: 60rpx;" :src="item.url" mode=""></image>
									<view style="margin-left: 20rpx;">{{item.name}}</view>
									<view style="margin-left: 20rpx;" v-show="item.name=='支付宝'">
										{{bangState?zfbNum:'请先绑定支付宝'}}
									</view>
									<view style="margin-left: 20rpx;" v-show="item.name=='微信'">
										{{wxbangState?zfbNum:'请先绑定微信'}}
									</view>
								</view>
								<fui-radio :checked="item.checked" :value="item.value">
								</fui-radio>
							</view>
						</fui-list-cell>
					</fui-label>
				</fui-radio-group>

				<!-- 绑定支付宝 -->
				<fui-modal :buttons="[]" width="700" maskClosable :show="data.zfbShow" @cancel="data.zfbShow=false">
					<text class="fui-title">上传支付宝二维码</text>
					<uni-file-picker :auto-upload="false" ref="files" style="margin-top: 20rpx;"
						@delete="deconsteZfb" @select="successZfb" file-mediatype="image" mode="grid" :limit="1" />
					<fui-button text="提交" width="240rpx" height="72rpx" :size="28" radius="36rpx" borderWidth="0"
						:margin="['48rpx','0','24rpx']" @click="zfbUpload">
					</fui-button>
				</fui-modal>
				<!-- 绑定支付宝 -->
				<fui-modal :buttons="[]" width="700" maskClosable :show="data.wxShow" @cancel="data.wxShow=false">
					<text class="fui-title">上传微信二维码</text>

					<uni-file-picker :auto-upload="false" ref="files" style="margin-top: 20rpx;"
						@delete="deconsteWx" @select="successWx" file-mediatype="image" mode="grid" :limit="1" />

					<fui-button text="提交" width="240rpx" height="72rpx" :size="28" radius="36rpx" borderWidth="0"
						:margin="['48rpx','0','24rpx']" @click="wxUpload">
					</fui-button>
				</fui-modal>
			</view>
			<!-- 提现按钮 -->
			<fui-button @click="topupDebounce()" style="padding: 0;margin-top: 40rpx;" text="立即提现"></fui-button>
			<!-- 提现描述 -->
			<view class="detail">
				<view class="detail_list" v-for="(item,index) in config.withdrawExplain" :key="index">
					{{index+1}}.{{item}}
				</view>
			</view>
			<fui-loading v-if="data.loading" :isFixed="true" srcCol="/static/images/component/loading_white.png"
				text="正在加载..."></fui-loading>
		</view>
	</view>
</template>

<script setup>
	import uQRCode from "@/utils/uqrcode.js"
	import { ref, reactive, computed } from 'vue'
	import { onLoad } from "@dcloudio/uni-app";
	import { useUploadFile } from '@/hooks/useUploadFile.js'
	const { uploadFile, deleteFile, getFileInfo } = useUploadFile()
	// 防抖
	import { debounce } from "@/utils/index.js"
	// 获取全局配置项
	import { ConfigStore } from "@/store/modules/config.js";
	// 获取用户信息
	import { LoginStore } from "@/store/modules/login.js";
	// 获取提现接口
	const qcpayApi = uniCloud.importObject('qc-pay', { customUI: true })
	// 绑定支付宝
	const qcuserApi = uniCloud.importObject('qc-user', {
		customUI: true // 取消自动展示的交互提示界面
	})
	const userInfo = computed(() => (LoginStore().userInfo))
	const config = computed(() => (ConfigStore().config))

	//提现类型数据
	const data = reactive({
		wxShow:false,
		moneyType: 'income_balance', //金额类型
		moneyItems: [{
			name: '收入余额',
			value: 'income_balance',
			checked: true
		}, {
			name: '充值余额',
			value: 'topup_balance',
			checked: false
		}],
		price: '', //提现金额
		radioItems: [{
			url: '../../../static/zfb.png',
			name: '支付宝',
			value: 'alipay',
			checked: false
		}, {
			url: '../../../static/wx.png',
			name: '微信',
			value: 'wxpay',
			checked: false
		}], //提现方式
		priceIndex: 0, //选项金额的下标
		payType: '', //提现渠道类型
		zfbShow: false, //支付宝绑定弹窗状态
		loading: false, //loaing
		wxShow: false, //绑定微信提示窗
		wxImg: "", //微信绑定图片
		buttons: [{
			//按钮文本
			text: '手动复制',
			//按钮字体颜色，可选
			color: '#333'
		}, {
			//按钮文本
			text: '自动跳转',
			//按钮字体颜色
			color: '#465CFF'
		}]
	})
	//切换提现类型
	const changemoneyType = (e) => {
		data.moneyType = e.detail.value
	}
	onLoad(async () => {
		// 获取指定提现金额
		if(config?.value?.assignMoney){
			data.price = Number(config?.value?.assignMoney[0]) || ""
		}

		//判断支付类型
		// data.radioItems.forEach((item, index) => {
		// 	if (!config.value.withdrawTypes.includes(item.value)) {
		// 		data.radioItems.splice(index, 1)
		// 	}
		// })
		data.radioItems = data.radioItems.filter(item => config.value.withdrawTypes.includes(item.value));
		if (data.radioItems.length == 1) {
			data.payType = data.radioItems[0].value
		}
		LoginStore().updateUserInfo()
	})
	
	//绑定支付宝二维码
	const zfbUpload = async()=>{
		if(fileIDZfb.length==0){
			uni.fui.toast('请上传二维码图片')
		}else{
			const res = await qcuserApi.bindingAccount({
				user_id:userInfo.value._id,
				zfb:fileIDZfb[0].fileID
			})
			uni.fui.toast(res.errMsg)
			data.zfbShow = false
			LoginStore().updateUserInfo()
		}
	}
	//绑定微信二维码
	const wxUpload = async()=>{
		if(fileIDWx.length==0){
			uni.fui.toast('请上传二维码图片')
		}else{
			const res = await qcuserApi.bindingAccount({
				user_id:userInfo.value._id,
				wx:fileIDWx[0].fileID
			})
			uni.fui.toast(res.errMsg)
			data.wxShow = false
			LoginStore().updateUserInfo()
		}
	}
	//上传二维码图片
	let fileIDZfb = []
	const successZfb = async (e) => {
		const res = await uploadFile(e.tempFiles, 'application', 'url')
		fileIDZfb = res
		uni.fui.toast(res.errMsg)
	}
	const deconsteZfb = (e) => {
		deleteFile(fileIDZfb, e)
		fileIDZfb.forEach((vm, i) => {
			if (vm.filePath == e.tempFilePath) {
				fileIDZfb.splice(i, 1)
			}
		})
	}
	let fileIDWx = []
	const successWx = async (e) => {
		const res = await uploadFile(e.tempFiles, 'application', 'url')
		fileIDWx = res
	}
	const deconsteWx = (e) => {
		deleteFile(fileIDWx, e)
		fileIDWx.forEach((vm, i) => {
			if (vm.filePath == e.tempFilePath) {
				fileIDWx.splice(i, 1)
			}
		})
	}
	// 点击选项卡切换金额
	const roof = (item, index) => {
		data.priceIndex = index
		data.price = item
	}

	// 查看资金明细
	const detail = () => {
		uni.navigateTo({
			url: '/pages/user/baldetail/baldetail'
		})
	}
	// 选择提现渠道方式
	const changepayType = (e) => {
		data.payType = e.detail.value
		// 如果选择了支付宝，且没有绑定支付宝，就打开弹窗绑定
		if (data.payType == "alipay" && !userInfo?.value?.zfb) {
			zfbCancel()
		}else if(data.payType == "wxpay" && !wxbangState.value){
			wxCancel()
		}
	}

	//提交支付宝信息
	const wxbangState = ref(userInfo?.value?.wx ? true : false)
	const bangState = ref(userInfo?.value?.zfb ? true : false) //绑定状态
	// 关闭弹窗
	const close = () => {
		data.sqshow = false
		data.radioItems[0].checked = false
	}
	//绑定支付宝信息
	const zfbCancel = async () => {
		data.zfbShow = true
	}
	//绑定微信信息
	const wxCancel = ()=>{
		data.wxShow = true
	}

	// 发起提现
	const topup = () => {
		var regNumber = /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/;
		if (!data.price) return uni.fui.toast('请输入提现金额')
		if (!regNumber.test(data.price)) return uni.fui.toast('请输入不为负数和0的金额')
		if (data.price < Number(config?.value?.minWithdraw)) return uni.fui.toast(
			`最小提现金额为${config?.value?.minWithdraw}`)
		if (!data.payType) return uni.fui.toast('请选择提现方式')
		// 充值余额可以提现的情况下
		if (config?.value?.rechargeRemit || userInfo?.value?.money?.topup_state) {
			// 判断选择的是充值余额还是收入余额
			if (data.moneyType == "income_balance") {
				// 如果提现的金额大于账户余额
				if (data.price > Number(userInfo?.value?.money?.income_balance)) return uni.fui.toast('收入余额不足')
				withdraw()
			} else {
				if (!userInfo?.value?.money?.topup_balance) return uni.fui.toast('可提现余额不足')
				if (data.price > Number(userInfo?.value?.money?.topup_balance)) return uni.fui.toast('充值余额不足')
				withdraw()
			}
		} else if (data.payType == "alipay") {
			if (!userInfo.value?.money?.income_state) return uni.fui.toast('暂不可提现')
			//重置提现类型 默认为incomeRemit
			data.moneyType = 'income_balance'
			if (bangState.value) {
				if (!data.price) return uni.fui.toast('请输入提现金额')
				if (data.price > Number(userInfo.value?.money?.income_balance)) return uni.fui.toast('余额不足')
				withdraw()
			} else {
				zfbCancel()
			}
		} else if (data.payType == 'wxpay') {
			if (data.price > 500) {
				return uni.fui.toast('微信单笔提现最大为500元')
			}
			if (wxbangState.value) {
				if (!data.price) return uni.fui.toast('请输入提现金额')
				if (data.price > Number(userInfo.value?.money?.income_balance)) return uni.fui.toast('余额不足')
				withdraw()
			} else {
				wxCancel()
			}
		}
	}
	// 提现防抖
	const topupDebounce = debounce(topup, 500)

	// 提现接口
	const withdraw = async () => {
		try {
			data.loading = true
			const res = await qcpayApi.withdraw({
				user_id: userInfo?.value?._id, //用户id
				moneyType: data.moneyType, //提现类型
				withdrawal_amount: Number(data.price), //提现金额
				withdrawal_method: data.payType //提现方式
			})
			if (res.errCode == 0) {
				LoginStore().updateUserInfo()
			}
			data.loading = false
			uni.fui.toast(res.errMsg)
		} catch (e) {
			if (e.errMsg == "请先绑定微信" && !userInfo?.value?.wx_openid) {
				data.wxShow = true
			}
			//TODO handle the exception
			data.loading = false
		}


	}

	//保存到相册
	const saveCode = (e) => {
		// #ifdef APP-PLUS
		const bitmap = new plus.nativeObj.Bitmap("test");
		bitmap.loadBase64Data(e, function() {
			const url = `_doc/qrcode_id_${new Date().getTime()}.png`; // url为时间戳命名方式
			bitmap.save(url, {
				overwrite: true, // 是否覆盖
			}, (i) => {
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: function() {
						uni.fui.toast('图片保存成功')
						bitmap.clear()
					}
				});
			}, (e) => {
				uni.fui.toast('图片保存失败')
				bitmap.clear()
			});
		}, (e) => {
			bitmap.clear()
		});
		// #endif

	}




	// #ifdef H5
	function leftClick() {
		uni.navigateBack()
	}
	// #endif
</script>

<style lang="scss" scoped>
	::v-deep .uni-file-picker__container{
		display: flex;
		justify-content: center;
	}
	::v-deep .file-picker__box-content {
		background-color: #f8f9f9;
	}
	.fui-desc {
		padding: 32rpx;
		font-size: 30rpx;
		line-height: 48rpx;
		font-weight: 400;
		color: #333333;
		box-sizing: border-box;
	}

	.yes1 {
		width: 42vw;
		background-color: #f1f4fa;
		padding: 20rpx 10rpx;
		border-radius: 20rpx;
	}

	.yes {
		height: 60rpx;
		line-height: 60rpx;
	}

	.no {
		width: 42vw;
		text-align: right;
		background-color: #f1f4fa;
		padding: 20rpx 10rpx;
		border-radius: 20rpx;
	}

	.yestwo {
		width: 40%;
		padding: 20rpx;
		display: flex;
		flex-wrap: wrap;
		align-items: center;
	}

	.line {
		width: 1px;
		height: 110rpx;
		background-color: #ccc;
	}

	.head {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0rpx;
	}

	.fui-list__cell {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.detail {
		margin-top: 40rpx;
		border-radius: 16rpx;
		padding: 32rpx;
		color: var(--fui-color-subtitle);
		background-color: #f1f4fa;
	}

	.box {
		padding: 32rpx;
		min-height: calc(100vh - 70rpx);
		background-color: #fff;
	}


	.btn {
		height: 40rpx;
		display: flex;
		align-items: center;
		text-align: center;
		padding: 10rpx 20rpx;
		color: var(--fui-color-primary);
		background-color: #f1f4fa;
		border-radius: 30rpx;
	}

	.rooflist {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.roofitem {
		display: flex;
		width: 26%;
		flex-direction: column;
		align-items: center;
		justify-content: space-around;
		background-color: #f3f5f7;
		margin-top: 20rpx;
		padding: 22rpx 22rpx;
		border-radius: 16rpx;
	}

	.roofactive {
		border: 1px solid var(--fui-color-primary);
	}

	.roofname {
		color: var(--fui-color-subtitle);
		font-size: 26rpx;
	}

	.roofprice {
		color: var(--fui-color-primary);
		font-weight: bold;
		font-size: 40rpx;
	}
</style>